package cc.springai.openai.controller;

import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api")
public class ApiController {

    String apiKey;
    String baseUrl;

    public ApiController() {
        this.apiKey = System.getenv("API_KEY");
        this.baseUrl = System.getenv("BASE_URL");
    }

    @RequestMapping("chat")
    public String chat() {
        String requestBody = "{\"model\":\"gpt-4.1\",\"stream\":false,\"messages\":[{\"role\":\"developer\",\"content\":\"You are a helpful assistant.\"},{\"role\":\"user\",\"content\":\"tell a joke\"}]}";
        Request request = new Request.Builder()
                .url(baseUrl)
                .header("Authorization", "Bearer " + apiKey)
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody))
                .build();

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS) // 设置连接超时为20秒
                .readTimeout(30, TimeUnit.SECONDS)   // 设置读取超时为30秒
                .writeTimeout(15, TimeUnit.SECONDS)  // 设置写入超时为15秒
                .build();
        try (Response response = client.newCall(request).execute()) {
            // 这里直接返回，方便大家查看数据结构
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    @RequestMapping("stream")
    public SseEmitter stream() {
        SseEmitter sseEmitter = sseInvoke();
        return sseEmitter;
    }

    private SseEmitter sseInvoke() {
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        // 创建监听器
        EventSourceListener listener = new EventSourceListener() {
            @Override
            public void onOpen(EventSource eventSource, Response response) {
                System.out.println("sse连接成功");
            }

            @Override
            public void onClosed(EventSource eventSource) {
                System.out.println("sse连接关闭！");
                sseEmitter.complete();
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                try {
                    sseEmitter.send(data);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                t.printStackTrace();
                if (t != null) {
                    System.out.println("sseInvoke error");
                } else if (response != null) {
                    System.out.println("sse连接失败，响应消息：" + response.message());
                }
                // 调用保存用户对话信息
                sseEmitter.complete();
            }
        };

        String requestBody = "{\"model\":\"gpt-4.1\",\"stream\":true,\"messages\":[{\"role\":\"developer\",\"content\":\"You are a helpful assistant.\"},{\"role\":\"user\",\"content\":\"tell a joke\"}]}";

        // 创建request对象
        Request request = new Request.Builder()
                .url(baseUrl)
                .header("Authorization", "Bearer " + apiKey)
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody))
                .build();
        System.out.println("请求参数：" + request.toString() + "；body：" + requestBody);

        // 创建 OkHttpClient 对象
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS) // 设置连接超时为20秒
                .readTimeout(30, TimeUnit.SECONDS)   // 设置读取超时为30秒
                .writeTimeout(15, TimeUnit.SECONDS)  // 设置写入超时为15秒
                .build();
        EventSource.Factory factory = EventSources.createFactory(client);
        factory.newEventSource(request, listener);

        return sseEmitter;
    }
}
